package br.com.webcrm.dao.impl;

import java.sql.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import br.com.webcrm.dao.ViewEventoDAO;
import br.com.webcrm.model.ViewEvento;
import br.com.webcrm.model.enuns.TipoDestinoEnum;

@Repository(value = "viewEventoDAO")
public class ViewEventoDAOImpl extends BaseDAOImpl<ViewEvento, Integer>
		implements ViewEventoDAO {

	@Autowired
	public ViewEventoDAOImpl(@Qualifier("sessionFactory") SessionFactory factory) {
		super.setSessionFactory(factory);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ViewEvento> consultarPorDataOrigem(Date dataInicial,
			Date dataFinal, Integer iddestino, String tipo_destino,
			Boolean apenasNaoFinalizados) {
		Criteria crit = getSession().createCriteria(ViewEvento.class);
		crit.add(Restrictions.eq("idDestino", iddestino));
		crit.add(Restrictions.eq("tipoDestino", tipo_destino));		
		crit.add(Restrictions.in("idStatusEvento", new Object[] { 1, 4, 5, 6 }));
		crit.add(Restrictions.between("dataOrigem", dataInicial, dataFinal));
		List<ViewEvento> lista = crit.list();
		return lista;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ViewEvento> consultarPorDataPrevista(Date dataInicial,
			Date dataFinal, Integer iddestino, Integer grupoDestino,Boolean apenasNaoFinalizados) {		
		Criteria crit = getSession().createCriteria(ViewEvento.class);
	    
		if (iddestino != 9999){
			crit.add(Restrictions.or(Restrictions.sqlRestriction("(id_destino = " + iddestino + " and tipo_destino = '" + TipoDestinoEnum.U.toString() + "')")
					, Restrictions.sqlRestriction("(id_destino = " + grupoDestino + " and tipo_destino = '" + TipoDestinoEnum.G.toString()  + "')" )));
		}else{
			crit.add(Restrictions.sqlRestriction("(id_destino = " + grupoDestino + " and tipo_destino = '" + TipoDestinoEnum.G.toString()  + "')" ));
		}	
		if (apenasNaoFinalizados){
			crit.add(Restrictions.in("idStatusEvento", new Object[] { 1, 4, 5, 6 }));
			crit.add( Restrictions.or(
					Restrictions.between("dataPrevista", dataInicial, dataFinal),
		            Restrictions.sqlRestriction("data_exibir <= current_timestamp")) );			
		}else{
			crit.add(Restrictions.between("dataPrevista", dataInicial, dataFinal));
		}
		System.out.println(crit.toString());		
	    List<ViewEvento> lista = crit.list();	   
	    return lista;		
	}

	@Override
	public List<ViewEvento> consultarEventosPorIdCliente(Integer idCliente) {
		String[] nomes = {"idCliente"};
		Object[] valores = {idCliente};
		return this.consultarPorNamedQueryEParametros("ViewEvento.findByIdCliente", nomes, valores);
	}

}
